/*
 * Copyright (c) 2010-2011, okazoh_tk. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *  - Neither the name of the copyright holder nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "alkes/codec/PngDecoder.h"
#include "alkes/codec/PngUtil.h"
#include "alkes/core/FileStream.h"

namespace alkes {

static void read_png_data(void* opaque, void* data, size_t count);

PngDecoder::PngDecoder(ImageBufferFactory* factory)
: ImageDecoder(factory)
{
}

PngDecoder::~PngDecoder()
{
}

bool PngDecoder::onDecode(const char* imagefile)
{
    FileStream stream(imagefile, AL_ACCESS_READ, AL_OPEN_EXISTING);

    if (!stream.canRead())
        return false;

    bool ret = decodePng(stream);

    stream.close();

    return ret;
}

bool PngDecoder::onDecode(const void* /*address*/, uint32_t /*size*/)
{
    AL_NO_SUPPORT(__FUNC_NAME__);
    return false;
}

bool PngDecoder::decodePng(Stream& stream)
{
    PngReader reader;

    if (0 != alkes_create_png_reader(&stream, read_png_data, &reader))
        return false;

    bool ret = false;
    uint16_t width, height;
    int32_t bit_depth, color_type;
    uint8_t channels;

    if (0 != alkes_get_png_info(reader, &width, &height, &bit_depth, &color_type, &channels))
    {
		alkes_destroy_png_reader(reader);
		return false;
	}

    PixelFormat format = AL_PIXEL_FORMAT_UNKNOWN;
    uint32_t trans = 0;

    if (channels == 16)
        trans |= AL_PNGTRANS_STRIP_16;

    if (PNG_COLOR_TYPE_GRAY == color_type)
    {
        if (channels < 8)
            trans |= AL_PNGTRANS_PACKING;

        format = AL_PIXEL_FORMAT_A8;
    }
    else if (PNG_COLOR_TYPE_RGB == color_type)
    {
        if (channels < 8)
            trans |= AL_PNGTRANS_PACKING;

        format = AL_PIXEL_FORMAT_RGB888;
    }
    else if (PNG_COLOR_TYPE_RGB_ALPHA == color_type)
    {
        if (channels < 8)
            trans |= AL_PNGTRANS_PACKING;

        format = AL_PIXEL_FORMAT_RGBA8888;
    }

    if (AL_PIXEL_FORMAT_UNKNOWN != format)
	{
        ImageBuffer* buffer = createImageBuffer(width, height, format);
        if (buffer)
        {
            int32_t pitch;
            void* ptr = buffer->lockRect(0, AL_LOCKMODE_WRITE, &pitch);
            if (ptr)
            {
                if (0 == alkes_decode_png(reader, ptr, pitch, height, trans))
                {
                    ret = true;
                }
                buffer->unlockRect();
            }

            if (!ret || false == registerImageBuffer(buffer))
            {
                buffer->release();
                ret = false;
            }
	    }
    }

    alkes_destroy_png_reader(reader);

    return ret;
}

static void read_png_data(void* opaque, void* data, size_t count)
{
    alkes::Stream* stream = (alkes::Stream*)opaque;
    stream->read((uint32_t)count, data);
}


}
